package com.cdream.basic.java8;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;
@Slf4j
public class FunctionUtil {
    private static final int DEFAULT_RETRY_TIME = 3;
    private static final long DEFAULT_SLEEP_TIME = 2L;

    public static <T> T retry(Supplier<T> supplier, int retryTimes, long sleepTime) {
        for (int i = 1; i < retryTimes; i++) {
            try {
                return supplier.get();
            } catch (Exception e) {
                ThreadUtil.sleep(sleepTime * 1000);
            }
        }
        return supplier.get();
    }

    public static <T> T retry(Supplier<T> supplier, int retryTimes) {
        return retry(supplier, retryTimes, DEFAULT_SLEEP_TIME);
    }

    public static <T> T retry(Supplier<T> supplier, long sleepTime) {
        return retry(supplier, DEFAULT_RETRY_TIME, sleepTime);
    }

    public static <T> T retry(Supplier<T> supplier) {
        return retry(supplier, DEFAULT_RETRY_TIME, DEFAULT_SLEEP_TIME);
    }

    public static void main(String[] args) {
        String dog = retry(() -> {
            System.out.println("dog");
            log.info("hahaha");
            return "dog";
        });
    }
}
